<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>使用jsonp获取腾讯天气信息</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        .container {
            padding-top: 15px;
        }

        h3 {
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="container">
        <h3>腾讯天气</h3>
        <table class="table table-striped table-hover" align="center" id="box">

        </table>
    </div>
    <script src="../js/jsonp.js"></script>
    <script src="../js/template-web.js"></script>
    <script type="text/html" id="tpl">
        <tr>
            <th>时间</th>
            <th>温度</th>
            <th>天气</th>
            <th>风向</th>
            <th>风力</th>
        </tr>
        {{each info}}
        <tr>
            <td>{{$value.update_time}}</td>
            <td>{{$value.degree}}</td>
            <td>{{$value.weather}}</td>
            <td>{{$value.wind_direction}}</td>
            <td>{{$value.wind_power}}</td>
        </tr>
        {{/each}}
            
    </script>
    <script>
        function dateFormat(date) {
            var yy = date.substr(0, 4);
            var mm = date.substr(4, 2);
            var dd = date.substr(6, 2);
            var hh = date.substr(8, 2);
            var mi = date.substr(10, 2);
            var ss = date.substr(12, 2);
            console.log(date)
            return `${yy}年${mm}月${dd}日${hh}时${mi}分${ss}秒`
        }
        //向模板中开放外部变量
        // template.defaults.imports.dateFormat = dateFormat;
        // 获取table标签
        const box = document.getElementById('box')
        // 定义jsonp请求成功后的回调函数
        const success = (res) => {
            if (res.status === 200) {
                var { data: data } = res
            }
            for (let k in data.forecast_1h) {
                data.forecast_1h[k].update_time = dateFormat(data.forecast_1h[k].update_time)
            }
            const table = template('tpl', { info: data.forecast_1h })
            // console.log(table)
            box.innerHTML = table
        }
        jsonp({
            // 请求地址
            url: 'https://wis.qq.com/weather/common',
            // data对象：向服务器端发送的请求参数
            data: {
                source: 'pc',
                weather_type: 'forecast_1h',//未来48小时
                // weather_type: 'forecast_1h|forecast_24h',//未来48小时以及未来七天
                province: '广东省',
                city: '广州市'
            },
            success: success
        })
    </script>
</body>